package com.zsjt.yysapi.common.controller;

import com.tencentcloudapi.common.exception.TencentCloudSDKException;
import com.zsjt.yysapi.common.config.TencentApiSmsConfig;
import com.zsjt.yysapi.common.constant.Constants;
import com.zsjt.yysapi.common.model.AjaxResult;
import com.zsjt.yysapi.common.util.CaptchaUtil;
import com.zsjt.yysapi.common.util.redis.RedisCache;
import com.zsjt.yysapi.common.util.uuid.IdUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Random;
import java.util.concurrent.TimeUnit;

/**
 * <p>
 * 验证码
 * </p>
 *
 * @author zsq
 * @since 2021-03-23
 */
@Api(tags = "验证码")
@RestController
@RequestMapping("/common/captcha")
public class CaptchaController {

    @Autowired
    private RedisCache redisCache;
    @Autowired
    private CaptchaUtil captchaUtil;
    @Autowired
    private TencentApiSmsConfig tencentApiSmsConfig;

    /**
     * 验证码
     *
     * @return
     */
    @ApiOperation("获取验证码")
    @GetMapping
    public AjaxResult generate(String phone) throws TencentCloudSDKException {
        String uuid = IdUtils.simpleUUID();
        String verifyKey = Constants.CAPTCHA_CODE_KEY + uuid;
        String code = createCode();
        if (captchaUtil.tencentSendSms(phone, code)) {
            // 保存验证码缓存
            redisCache.setCacheObject(verifyKey, code, Integer.valueOf(tencentApiSmsConfig.getExpireTime()), TimeUnit.MINUTES);
            AjaxResult res = AjaxResult.success();
            res.put("uuid", uuid);
            return res;
        }
        return AjaxResult.error("验证码获取失败");
    }

    /**
     * 生成随机六位数
     *
     * @return
     */
    private String createCode() {
        //生成随机六位数
        Random random = new Random();
        StringBuilder code = new StringBuilder();
        for (
                int i = 0;
                i < 6; i++) {
            code.append(random.nextInt(10));
        }
        return code.toString();
    }
}
